﻿Imports System.Net
Imports System.IO
Imports org.codegen.common.Encryption

''' <summary>
''' This is a utility class which downloads the system backup from the 
''' application web site
''' </summary>
''' <remarks></remarks>
Public Class DBRestoreBackup

    Private zipfilename As String

    Public Sub downloadBackup()

        Dim onlineDBbackupLocation = SimpleEncrypt.Decipher(My.Settings.dbOnlineBackupLocation)
        Me.zipfilename = SimpleEncrypt.Decipher(My.Settings.dbBackupDir) & _
                            My.Settings.dbName & ".downloaded.zip"

        Dim x As WebClient = New WebClient()
        x.DownloadFile(New System.Uri(onlineDBbackupLocation), zipfilename)


        Dim fi As FileInfo = New FileInfo(Me.zipfilename)

        Dim zipFilePackage As System.IO.Packaging.Package =
                   System.IO.Packaging.ZipPackage.Open(Me.zipfilename,
                   System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite)

        'Iterate through the all the files that 
        'is added within the collection and 
        For Each contentFile As System.IO.Packaging.ZipPackagePart
                      In zipFilePackage.GetParts()

            createFile(fi.DirectoryName, contentFile)

        Next


    End Sub

    Protected Sub createFile(ByVal rootFolder As String, _
                             ByVal contentFile As System.IO.Packaging.ZipPackagePart)

        ' Initially create file under the folder specified
        Dim contentFilePath As String = String.Empty
        contentFilePath = contentFile.Uri.OriginalString.Replace("/"c, _
                                                                 System.IO.Path.DirectorySeparatorChar)

        If contentFilePath.StartsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
            contentFilePath = contentFilePath.TrimStart(System.IO.Path.DirectorySeparatorChar)
            'do nothing
        Else

        End If

        contentFilePath = System.IO.Path.Combine(rootFolder, contentFilePath)

        'Check for the folder already exists. If not then create that folder
        If System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(contentFilePath)) <> True Then
            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(contentFilePath))
            'do nothing
        Else
        End If

        Dim newFileStream As System.IO.FileStream = System.IO.File.Create(contentFilePath)
        newFileStream.Close()
        Dim content As Byte() = New Byte(CInt(contentFile.GetStream().Length - 1)) {}
        contentFile.GetStream().Read(content, 0, content.Length)
        System.IO.File.WriteAllBytes(contentFilePath, content)

    End Sub

End Class
